package org.linlinjava.litemall.admin.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import java.math.BigDecimal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.AdminHerbService;
import org.linlinjava.litemall.admin.service.AdminPurchaseService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.LitemallAddressService;
import org.linlinjava.litemall.db.service.LitemallFormPurchaseItemService;
import org.linlinjava.litemall.db.service.LitemallHerbService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.*;

@RestController
@RequestMapping("/admin/purchase")
@Validated
public class AdminPurchaseController {
    private final Log logger = LogFactory.getLog(AdminGoodsController.class);

    @Autowired
    private AdminPurchaseService adminPurchaseService;

    @Autowired
    private LitemallFormPurchaseItemService litemallFormPurchaseItemService;

    @Autowired
    private LitemallShopService litemallShopService;

    @Autowired
    private LitemallHerbService litemallHerbService;

    @Autowired
    private LitemallAddressService litemallAddressService;

    /**
     * 查询
     *
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:purchase:list")
    @RequiresPermissionsDesc(menu = {"供求信息", "我的采购"}, button = "查询")
    @GetMapping("/list")
    public Object list(String status,String sort,
                       String startTime,String endTime,String needHerb,
                       String order, boolean selectAll,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit
    ) {
        return ResponseUtil.okList(adminPurchaseService.list(status,sort,startTime,endTime,needHerb,order,page,limit,selectAll));
    }

    /**
     * 查询药材
     *
     * @param codeList
     * @return
     */
    @RequiresPermissions("admin:purchase:queryHerb")
    @RequiresPermissionsDesc(menu = {"供求信息", "我的采购"}, button = "查询药材")
    @PostMapping("/queryHerb")
    public Object queryHerb(@RequestBody List<String> codeList) {
        List<LitemallHerb> herbLists = new ArrayList<>();
        int count = 2;
        for (String code:codeList) {
            List<LitemallHerb> herbList = litemallHerbService.queryHerbByCode(code);
            if (herbList.size() == 0) {
                return ResponseUtil.fail(HERB_CODE_EXIST, "第"+count+"行,编号不存在");
            }else {
                herbLists.add(herbList.get(0));
            }
            count++;
        }
        return ResponseUtil.ok(herbLists);
    }

    /**
     * 查询地址
     *
     * @return
     */
    @RequiresPermissions("admin:purchase:queryAddress")
    @RequiresPermissionsDesc(menu = {"供求信息", "我的采购"}, button = "查询地址")
    @PostMapping("/queryAddress")
    public Object queryAddress() {
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        LitemallShop Shop =litemallShopService.findById(admin.getShopId());
        if(Shop==null){
            return ResponseUtil.fail(ADMIN_ADDRESS_EXIST, "未获取到商户信息,请勿使用管理员账号发布");
        }
        List<LitemallAddress> addressList=litemallAddressService.queryBySid(Shop.getId());
        if(addressList.size()>0){
            return ResponseUtil.ok(addressList);
        }else {
            return ResponseUtil.ok();
        }
    }

    /**
     * 新增
     *
     * @param map
     * @return
     */
    @RequiresPermissions("admin:purchase:create")
    @RequiresPermissionsDesc(menu = {"供求信息", "我的采购"}, button = "新增")
    @PostMapping("/create")
    public Object create(@RequestBody Map<String,Object> map) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LinkedHashMap<String,?> dataForm = (LinkedHashMap<String, String>) map.get("dataForm");
        List<LinkedHashMap<String,?>> herbList= (List<LinkedHashMap<String, ?>>) map.get("herbList");

        LitemallFormPurchase purchase = new LitemallFormPurchase();
        purchase.setName(dataForm.get("name").toString());
        purchase.setAddressId(Integer.parseInt(dataForm.get("addressId").toString()));
        purchase.setStatus(Byte.parseByte(dataForm.get("status").toString()));
        purchase.setInventoryPlace(dataForm.get("inventoryplace").toString());
        purchase.setDueTime(LocalDateTime.parse(dataForm.get("dueTime").toString(), formatter));
        purchase.setContactName(dataForm.get("contactName").toString());
        purchase.setContactTel(dataForm.get("contactTel").toString());
        for (LinkedHashMap<String,?> herbMap:herbList) {
            if (!StringUtils.isEmpty(purchase.getNeedHerb())){
                purchase.setNeedHerb(
                        purchase.getNeedHerb()+","+
                                herbMap.get("herbName").toString()+herbMap.get("specifications").toString()+" "+
                                new BigDecimal(herbMap.get("needAmount").toString())+
                                herbMap.get("measurementUnit").toString()
                );
            }else {
                purchase.setNeedHerb(
                                herbMap.get("herbName").toString()+herbMap.get("specifications").toString()+" "+
                                new BigDecimal(herbMap.get("needAmount").toString())+
                                herbMap.get("measurementUnit").toString()
                );
            }
        }
        purchase = adminPurchaseService.add(purchase);


        List<LitemallFormPurchaseItem> ItemList= new ArrayList<>();
        for (LinkedHashMap<String,?> herbMap:herbList) {
            LitemallFormPurchaseItem purchaseItem = new LitemallFormPurchaseItem();
            purchaseItem.setFormPurchaseId(purchase.getId());
            purchaseItem.setHerbId(Integer.valueOf(herbMap.get("id").toString()));
            purchaseItem.setCode(herbMap.get("code").toString());
            purchaseItem.setHerbName(herbMap.get("herbName").toString());
            purchaseItem.setMeasurementUnit(herbMap.get("measurementUnit").toString());
            purchaseItem.setSpecifications(herbMap.get("specifications").toString());
            purchaseItem.setNeedAmount(new BigDecimal(herbMap.get("needAmount").toString()));
            purchaseItem.setStatus("0");
            purchaseItem.setCheckStatus("0");
            ItemList.add(purchaseItem);
        }
        litemallFormPurchaseItemService.batchInsert(ItemList);

        return ResponseUtil.ok(map);
    }


    /**
     * 查询收购药材
     *
     * @return
     */
    @RequiresPermissions("admin:purchase:queryPurchaseItem")
    @RequiresPermissionsDesc(menu = {"供求信息", "我的采购"}, button = "查询收购药材")
    @PostMapping("/queryPurchaseItem")
    public Object queryPurchaseItem(@RequestParam Integer purchaseId) {
        return ResponseUtil.ok(litemallFormPurchaseItemService.list(purchaseId));
    }


    /**
     * 编辑商品
     *
     * @return
     */
    @RequiresPermissions("admin:purchase:update")
    @RequiresPermissionsDesc(menu = {"供求信息", "我的采购"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody Map<String,Object> map) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LinkedHashMap<String,?> dataForm = (LinkedHashMap<String, String>) map.get("dataForm");
        List<LinkedHashMap<String,?>> herbList= (List<LinkedHashMap<String, ?>>) map.get("herbList");
        LitemallFormPurchase purchase = new LitemallFormPurchase();
        purchase.setName(dataForm.get("name").toString());
        purchase.setCode(dataForm.get("code").toString());
        purchase.setAddressId(Integer.parseInt(dataForm.get("addressId").toString()));
        purchase.setStatus(Byte.parseByte(dataForm.get("status").toString()));
        purchase.setInventoryPlace(dataForm.get("inventoryplace").toString());
        purchase.setDueTime(LocalDateTime.parse(dataForm.get("dueTime").toString(), formatter));
        purchase.setContactName(dataForm.get("contactName").toString());
        purchase.setContactTel(dataForm.get("contactTel").toString());
        purchase.setUserId(Integer.valueOf(dataForm.get("userId").toString()));
        purchase.setId(Integer.valueOf(dataForm.get("id").toString()));
        purchase.setShopId(Integer.valueOf(dataForm.get("shopId").toString()));
        purchase.setShopName(dataForm.get("shopName").toString());
        purchase.setUserType(Byte.valueOf(dataForm.get("userType").toString()));
        purchase.setAddTime(LocalDateTime.parse(dataForm.get("addTime").toString(), formatter));
        purchase.setNeedHerb(null);
        for (LinkedHashMap<String,?> herbMap:herbList) {


            if (!StringUtils.isEmpty(purchase.getNeedHerb())){
                purchase.setNeedHerb(
                        purchase.getNeedHerb()+","+
                                herbMap.get("herbName").toString()+herbMap.get("specifications").toString()+" "+
                                new BigDecimal(herbMap.get("needAmount").toString())+
                                herbMap.get("measurementUnit").toString()
                );
            }else {
                purchase.setNeedHerb(
                        herbMap.get("herbName").toString()+herbMap.get("specifications").toString()+" "+
                        new BigDecimal(herbMap.get("needAmount").toString())+
                        herbMap.get("measurementUnit").toString()
                );
            }
        }
        adminPurchaseService.updateById(purchase);

        litemallFormPurchaseItemService.batchInsert(purchase.getId());
        List<LitemallFormPurchaseItem> ItemList= new ArrayList<>();
        for (LinkedHashMap<String,?> herbMap:herbList) {
            LitemallFormPurchaseItem purchaseItem = new LitemallFormPurchaseItem();
            purchaseItem.setFormPurchaseId(purchase.getId());
            purchaseItem.setHerbId(Integer.valueOf(herbMap.get("herbId").toString()));
            purchaseItem.setCode(herbMap.get("code").toString());
            purchaseItem.setHerbName(herbMap.get("herbName").toString());
            purchaseItem.setMeasurementUnit(herbMap.get("measurementUnit").toString());
            purchaseItem.setSpecifications(herbMap.get("specifications").toString());
            purchaseItem.setNeedAmount(new BigDecimal(herbMap.get("needAmount").toString()));
            purchaseItem.setStatus("0");
            purchaseItem.setCheckStatus("0");
            ItemList.add(purchaseItem);
        }
        litemallFormPurchaseItemService.batchInsert(ItemList);

        return ResponseUtil.ok(map);
    }

    /**
     * 删除商品
     *
     * @param
     * @return
     */
    @RequiresPermissions("admin:purchase:delete")
    @RequiresPermissionsDesc(menu = {"供求信息", "我的采购"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallFormPurchase purchase) {
        purchase.setStatus((byte) 5);
        adminPurchaseService.updateById(purchase);
        return ResponseUtil.ok(purchase);
    }
    /**
     * 验证表单
     * @param purchaseExample
     * @return
     */
    private Object validate(LitemallFormPurchase purchaseExample) {
        String Remark = purchaseExample.getRemark();
        if (!StringUtils.isEmpty(Remark)) {
            return null;
        }
        int ShopId = purchaseExample.getShopId();
        if (StringUtils.isEmpty(ShopId)) {
            return null;
        }
        LocalDateTime dueTime = purchaseExample.getDueTime();
        if (StringUtils.isEmpty(dueTime)) {
            return null;
        }
        return ResponseUtil.badArgument();
    }

}
